#!/usr/bin/env swift
import Cocoa

// 简化版本的TopMostHost，避免复杂的指针操作

func main() {
    // 读取输入数据
    let input = FileHandle.standardInput
    let lengthData = input.readData(ofLength: 4)
    guard lengthData.count == 4 else {
        sendSimpleResponse("{\"ok\":false,\"status\":\"UNKNOWN\"}")
        return
    }
    
    // 手动解析长度（避免指针操作）
    let length = Int(lengthData[0]) + Int(lengthData[1]) * 256 + Int(lengthData[2]) * 65536 + Int(lengthData[3]) * 16777216
    let jsonData = input.readData(ofLength: length)
    
    // 尝试解析JSON
    guard let jsonString = String(data: jsonData, encoding: .utf8) else {
        sendSimpleResponse("{\"ok\":false,\"status\":\"UNKNOWN\"}")
        return
    }
    
    // 简单的命令解析（避免复杂的JSON处理）
    var command = "toggle"
    var extensionId = ""
    
    if jsonString.contains("\\\"command\\\":\\\"setup\\\"") {
        command = "setup"
        // 提取extension_id
        if let startIndex = jsonString.range(of: "\\\"extension_id\\\":\\\"")?.upperBound {
            if let endIndex = jsonString[startIndex...].range(of: "\\\"")?.lowerBound {
                extensionId = String(jsonString[startIndex..<endIndex])
            }
        }
    } else if jsonString.contains("\\\"command\\\":\\\"set\\\"") {
        command = "set"
    } else if jsonString.contains("\\\"command\\\":\\\"unset\\\"") {
        command = "unset"
    } else if jsonString.contains("\\\"command\\\":\\\"query\\\"") {
        command = "query"
    }
    
    // 处理命令
    if command == "setup" {
        handleSetup(extensionId: extensionId)
    } else {
        handleWindowCommand(command: command)
    }
}

func sendSimpleResponse(_ jsonString: String) {
    let data = jsonString.data(using: .utf8)! 
    let length = data.count
    
    // 创建4字节长度前缀（大端序）
    var lengthBytes = Data()
    lengthBytes.append(UInt8(length & 0xFF))
    lengthBytes.append(UInt8((length >> 8) & 0xFF))
    lengthBytes.append(UInt8((length >> 16) & 0xFF))
    lengthBytes.append(UInt8((length >> 24) & 0xFF))
    
    // 写入输出
    FileHandle.standardOutput.write(lengthBytes)
    FileHandle.standardOutput.write(data)
    FileHandle.standardOutput.synchronizeFile()
}

func handleWindowCommand(command: String) {
    // 使用状态文件来跟踪窗口置顶状态
    let homeDir = NSHomeDirectory()
    let stateFile = "\(homeDir)/.chrome_window_topmost_state"
    
    switch command {
    case "query":
        // 检查状态文件是否存在
        if FileManager.default.fileExists(atPath: stateFile) {
            sendSimpleResponse("{\"ok\":true,\"status\":\"TOPMOST\"}")
        } else {
            sendSimpleResponse("{\"ok\":true,\"status\":\"NOTOPMOST\"}")
        }
        return
        
    case "set":
        // 创建状态文件
        FileManager.default.createFile(atPath: stateFile, contents: nil)
        // 使用更强大的窗口激活脚本
        executeEnhancedActivation()
        sendSimpleResponse("{\"ok\":true,\"status\":\"TOPMOST\"}")
        return
        
    case "unset":
        // 删除状态文件
        try? FileManager.default.removeItem(atPath: stateFile)
        sendSimpleResponse("{\"ok\":true,\"status\":\"NOTOPMOST\"}")
        return
        
    default: // toggle
        // 切换状态
        if FileManager.default.fileExists(atPath: stateFile) {
            try? FileManager.default.removeItem(atPath: stateFile)
            sendSimpleResponse("{\"ok\":true,\"status\":\"NOTOPMOST\"}")
        } else {
            FileManager.default.createFile(atPath: stateFile, contents: nil)
            executeEnhancedActivation()
            sendSimpleResponse("{\"ok\":true,\"status\":\"TOPMOST\"}")
        }
        return
    }
}

func executeEnhancedActivation() {
    // 增强的窗口激活脚本，执行多次激活以确保效果
    let scripts = [
        // 先最小化然后恢复，确保窗口处于正常状态
        "tell application \"Google Chrome\" to set miniaturized of window 1 to false",
        // 多次设置为前台，增加成功率
        "tell application \"System Events\" to tell process \"Google Chrome\" to set frontmost to true",
        // 稍微延迟后再次设置
        "delay 0.1",
        "tell application \"System Events\" to tell process \"Google Chrome\" to set frontmost to true",
        // 聚焦Chrome窗口
        "tell application \"Google Chrome\" to activate"
    ]
    
    // 执行每个脚本
    for script in scripts {
        let task = Process()
        task.arguments = ["-e", script]
        task.executableURL = URL(fileURLWithPath: "/usr/bin/osascript")
        
        do {
            try task.run()
            task.waitUntilExit()
        } catch {
            // 忽略单个脚本的错误，继续执行其他脚本
        }
    }
}

func handleSetup(extensionId: String) {
    if extensionId.isEmpty {
        sendSimpleResponse("{\"ok\":false,\"status\":\"UNKNOWN\"}")
        return
    }
    
    let homeDir = NSHomeDirectory()
    let manifestDir = "\(homeDir)/Library/Application Support/Google/Chrome/NativeMessagingHosts"
    let manifestPath = "\(manifestDir)/com.topmost.chrome_window.json"
    
    // 创建目录
    do {
        try FileManager.default.createDirectory(atPath: manifestDir, withIntermediateDirectories: true)
        
        // 创建manifest内容
        let executablePath = "\(FileManager.default.currentDirectoryPath)/TopMostHost"
        let origin = "chrome-extension://\(extensionId)/"
        
        let manifestContent = """
        {
          "name": "com.topmost.chrome_window",
          "description": "Chrome窗口置顶原生主机",
          "path": "\(executablePath)",
          "type": "stdio",
          "allowed_origins": [
            "\(origin)"
          ]
        }
        """
        
        try manifestContent.write(toFile: manifestPath, atomically: true, encoding: .utf8)
        
        // 设置权限
        try runCommand("chmod +x \(executablePath)")
        
        sendSimpleResponse("{\"ok\":true,\"status\":\"SETUP_DONE\",\"manifestPath\":\"\(manifestPath)\",\"origin\":\"\(origin)\"}")
    } catch {
        sendSimpleResponse("{\"ok\":false,\"status\":\"SETUP_ERROR\"}")
    }
}

func runCommand(_ cmd: String) throws {
    let task = Process()
    let pipe = Pipe()
    
    task.standardOutput = pipe
    task.standardError = pipe
    task.arguments = ["-c", cmd]
    task.executableURL = URL(fileURLWithPath: "/bin/bash")
    
    try task.run()
    task.waitUntilExit()
}

// 运行主函数
main()
